package cn.itcast.n8;

import cn.itcast.n2.util.Sleeper;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.*;

/**
 * @author: AirMan
 * @date: 2025/4/22 16:22
 * @description:
 */
@Slf4j(topic = "c.TestTimerAndScheduled")
public class TestTimerAndScheduled {

    public static void main(String[] args) throws IOException, ExecutionException, InterruptedException {


        ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);

        Future<Boolean> f = executor.submit(() -> {
            log.debug("task 1");
            int i = 1 / 0;
            Sleeper.sleep(2);   // 上一个任务结束 <-> 延时 <-> 下一个任务开始
            return true;
        });
        Boolean b = f.get();

    }

    private static void scheduledAtFixedRate() {
        ScheduledExecutorService executor = Executors.newScheduledThreadPool(2);

        executor.scheduleAtFixedRate(() -> {
            log.debug("taks 1");
            Sleeper.sleep(2); // 由于任务执行时间 > 间隔时间，间隔被『撑』到了 2s
        }, 1, 1, TimeUnit.SECONDS);
    }

    private static void scheduledExecutorServiceToScheduled() {
        ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);

        executor.schedule(() -> {
            log.debug("task 1");
            Sleeper.sleep(2);
        }, 1000, TimeUnit.MILLISECONDS);

        executor.schedule(() -> {
            log.debug("task 2");
        }, 1000, TimeUnit.MILLISECONDS);
    }

    private static void timerTask() {
        Timer timer = new Timer();

        TimerTask task1 = new TimerTask() {
            @Override
            public void run() {
                log.debug("task 1");
            }
        };

        TimerTask task2 = new TimerTask() {
            @Override
            public void run() {
                log.debug("task 2");
            }
        };

        log.debug("start...");
        timer.schedule(task1, 1000);
        timer.schedule(task2, 1000);
    }
}
